package com.zys.sac.core.helper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis互斥token管理器，如果使用该token管理器，同一个用户将不允许重复登录
 *
 * Created by zhongjunkai on 2023/2/23.
 */
public class RedisMutexTokenManager implements TokenManager {

    @Autowired
    protected RedisTemplate<String, Object> redisTemplate;

    protected long expired;

    public RedisMutexTokenManager(long expired) {
        this.expired = expired;
    }


    @Override
    public String createAndSaveToken(UserDetails userDetails) {
        return this.createAndSaveToken(userDetails, this.expired);
    }

    @Override
    public String createAndSaveToken(UserDetails userDetails, long expired) {
        String token = generateToken(userDetails);
        String cacheKey = createCacheKey(token);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", userDetails);
        redisTemplate.delete(cacheKey);
        redisTemplate.opsForHash().putAll(cacheKey, map);
        redisTemplate.expire(cacheKey, expired, TimeUnit.SECONDS);
        return token;
    }

    @Override
    public void renewalToken(String token) {
        this.renewalToken(token, this.expired);
    }

    @Override
    public void renewalToken(String token, long expired) {
        String cacheKey = createCacheKey(token);
        redisTemplate.expire(cacheKey, expired, TimeUnit.SECONDS);
    }

    @Override
    public UserDetails getUserDetails(String token) {
        String cacheKey = createCacheKey(token);
        UserDetails user = (UserDetails) redisTemplate.opsForHash().get(cacheKey, "user");
        return user;
    }

    @Override
    public void invalidToken(String token) {
        String cacheKey = createCacheKey(token);
        redisTemplate.delete(cacheKey);
    }
}
